package com.example.piece.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.example.piece.constant.Key
import com.example.piece.entity.User
import com.example.piece.net.NetManager
import com.example.piece.repository.MainActivityRepository
import com.example.base.ext.LoadingView
import com.example.base.tools.ConfigTool
import com.example.base.vm.BaseViewModel
import com.example.base.vm.OnSuccess
import com.example.base.vm.requireValue

/**
 * 主页的 ViewModel
 */
class LoginViewModel(
    savedStateHandle: SavedStateHandle
) : BaseViewModel<MainActivityRepository>(savedStateHandle) {

    override fun createRepository(): MainActivityRepository = MainActivityRepository()

    var username: MutableLiveData<String> =
        getData(Key.DataKey.USERNAME, "")

    var password: MutableLiveData<String> =
        getData(Key.DataKey.PASSWORD, "")

    /**  用户登陆  **/
    fun login(
        loadingView: LoadingView,
        onSuccess: OnSuccess<User>
    ) =
        Launch(loadingView) {
            if (username.requireValue().isEmpty() || password.requireValue().isEmpty()) {
                onError("请将用户信息填写完整！")
                return@Launch
            }

            val result = repository.login(username.requireValue(), password.requireValue())
            if (result.code == NetManager.DATA_ERROR||result.code==NetManager.IN_MAINTENANCE) {
                onError(result.msg)
                return@Launch
            }

            // Save username and token
            ConfigTool.putValues(
                mutableMapOf(
                    Key.DataKey.USERNAME to username.requireValue(),
                    Key.DataKey.PASSWORD to password.requireValue(),
                    Key.DataKey.TOKEN to result.data.token
                )
            )

            onSuccess(result)
        }

    /**  退出登陆  **/
    fun logout(loadingView: LoadingView, onSuccess: OnSuccess<Unit>) = Launch(loadingView) {
        val result = repository.logout()
        onSuccess(result)
    }
}
